package tcp

import (
	"bufio"
	"fmt"
	"io"
	"log"
	"net"
	"strconv"
)

func ClientMain(localServer []int, remoteIP string) {
	remoteControlAddr := remoteIP + ":5005"
	tcpConn, err := CreateTCPConn(remoteControlAddr)
	if err != nil {
		log.Println("[连接失败]" + remoteControlAddr + err.Error())
		return
	}
	log.Println("[已连接]" + remoteControlAddr)

	reader := bufio.NewReader(tcpConn)
	for {
		s, err := reader.ReadString('\n')
		if err != nil || err == io.EOF {
			break
		}

		// 当有新连接信号出现时，新建一个tcp连接
		if s == NewConnection+"\n" {
			fmt.Println("connect to ecs",remoteIP)
			go connectLocalAndRemote(localServer,remoteIP)
		}
	}

	log.Println("[已断开]" + remoteControlAddr)
}

func connectLocalAndRemote(localServer []int, remoteIP string) {
	remote := connectRemote(remoteIP)
	for _,v:=range localServer{
		ip:="127.0.0.1:"+strconv.Itoa(v)
		fmt.Println("connect local server",ip)
		local:=connectLocal(ip)
		if local != nil && remote != nil {
			Join2Conn(local, remote,ip)
		} else {
			if local != nil {
				_ = local.Close()
			}
			if remote != nil {
				_ = remote.Close()
			}
		}
	}
	//local := connectLocal(localServer)
}

func connectLocal(localServer string) *net.TCPConn {
	conn, err := CreateTCPConn(localServer)
	if err != nil {
		log.Println("[连接本地服务失败]" + err.Error())
	}
	return conn
}

//通信端口
func connectRemote(remoteIP string) *net.TCPConn {
	remoteServerAddr := remoteIP + ":5006"
	conn, err := CreateTCPConn(remoteServerAddr)
	if err != nil {
		log.Println("[连接远端服务失败]" + err.Error())
	}
	return conn
}
